package com.eduagent.xwqeduagent.api.characterRecognition.PhotographySpeedCalculation.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eduagent.xwqeduagent.api.characterRecognition.PhotographySpeedCalculation.PhotographySpeedCalculationAPI;
import com.eduagent.xwqeduagent.api.characterRecognition.PhotographySpeedCalculation.PhotographySpeedCalculationResult;
import com.eduagent.xwqeduagent.api.characterRecognition.PhotographySpeedCalculation.PhotographySpeedCalculationResult.SpeedCalculationItem;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * 拍照速算识别示例类
 * 展示如何使用拍照速算识别API
 */
public class SpeedCalculationExample {
    // 应用ID（需从讯飞控制台获取）
    private static final String APPID = "637d1630";
    
    // 接口API Key（需从讯飞控制台获取）
    private static final String API_KEY = "8bd0514cb66802c719bbf34a908a0119";
    
    // 接口API Secret（需从讯飞控制台获取）
    private static final String API_SECRET = "NzUyY2Y3OTYwYjAyMGExODc5OTM1ZGZl";
    
    // 测试图片路径
    private static final String TEST_IMAGE_PATH = "resource/speed_calculation/test.jpg";
    
    public static void main(String[] args) {
        try {
            // 检查配置
            if (APPID.isEmpty() || API_KEY.isEmpty() || API_SECRET.isEmpty()) {
                System.out.println("请配置正确的APPID、API_KEY和API_SECRET");
                return;
            }
            
            // 检查测试文件
            File testFile = new File(TEST_IMAGE_PATH);
            if (!testFile.exists()) {
                System.out.println("测试文件不存在: " + TEST_IMAGE_PATH);
                return;
            }
            
            System.out.println("===== 开始拍照速算识别示例 =====");
            
            // 创建API实例
            PhotographySpeedCalculationAPI api = new PhotographySpeedCalculationAPI(APPID, API_KEY, API_SECRET);
            
            // 1. 从文件读取并识别
            System.out.println("\n1. 从文件识别:");
            String resultFromFile = api.recognizeFromFile(TEST_IMAGE_PATH);
            processResult(resultFromFile);
            
            // 2. 从字节数组识别
            System.out.println("\n2. 从字节数组识别:");
            byte[] imageBytes = Files.readAllBytes(Paths.get(TEST_IMAGE_PATH));
            String resultFromBytes = api.recognizeFromByteArray(imageBytes);
            processResult(resultFromBytes);
            
            // 3. 从Base64识别（读取文件并转为Base64）
            System.out.println("\n3. 从Base64识别:");
            String base64Image = java.util.Base64.getEncoder().encodeToString(imageBytes);
            String resultFromBase64 = api.recognizeFromBase64(base64Image);
            processResult(resultFromBase64);
            
            System.out.println("\n===== 拍照速算识别示例结束 =====");
            
        } catch (Exception e) {
            System.err.println("运行示例时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 处理识别结果
     * 
     * @param jsonResult JSON格式的识别结果
     */
    private static void processResult(String jsonResult) {
        try {
            // 解析JSON结果
            JSONObject jsonObj = JSON.parseObject(jsonResult);
            System.out.println("原始JSON结果: " + jsonObj.toJSONString());
            
            // 使用结果解析器解析
            PhotographySpeedCalculationResult result = PhotographySpeedCalculationResult.parseResult(jsonResult);
            
            if (result.isSuccess()) {
                System.out.println("识别成功!");
                System.out.println("会话ID: " + result.getSid());
                System.out.println("题型类别: " + result.getCategory());
                System.out.println("接口版本: " + result.getVersion());
                
                // 获取所有识别项目
                List<SpeedCalculationItem> items = result.getItems();
                System.out.println("识别到 " + items.size() + " 个速算题:");
                
                // 打印每个识别项目
                for (int i = 0; i < items.size(); i++) {
                    SpeedCalculationItem item = items.get(i);
                    System.out.println("  速算题 #" + (i + 1) + ":");
                    System.out.println("    内容: " + item.getContent());
                    System.out.println("    置信度: " + item.getConfidence());
                    System.out.println("    正误判断: " + (item.getTotalScore() == 1 ? "正确" : "错误"));
                    System.out.println("    拒识标志: " + (item.getRecRejection() == 0 ? "未拒识" : "已拒识"));
                    
                    // 打印位置信息
                    if (item.getRectangle() != null) {
                        System.out.println("    位置: (" + item.getRectangle().getLeftUpX() + "," + 
                                item.getRectangle().getLeftUpY() + ") - (" + 
                                item.getRectangle().getRightDownX() + "," + 
                                item.getRectangle().getRightDownY() + ")");
                    }
                }
                
                // 打印统计信息
                Map<String, Integer> statistics = result.getStatistics();
                System.out.println("统计信息:");
                System.out.println("  总计: " + statistics.get("total") + " 题");
                System.out.println("  正确: " + statistics.get("correct") + " 题");
                System.out.println("  错误: " + statistics.get("incorrect") + " 题");
                
                // 打印所有公式
                List<String> allFormulas = result.getAllFormulas();
                System.out.println("所有公式:");
                for (int i = 0; i < allFormulas.size(); i++) {
                    System.out.println("  " + (i + 1) + ". " + allFormulas.get(i));
                }
                
                // 打印正确公式
                List<String> correctFormulas = result.getCorrectFormulas();
                System.out.println("正确公式:");
                for (int i = 0; i < correctFormulas.size(); i++) {
                    System.out.println("  " + (i + 1) + ". " + correctFormulas.get(i));
                }
                
                // 打印错误公式
                List<String> incorrectFormulas = result.getIncorrectFormulas();
                System.out.println("错误公式:");
                for (int i = 0; i < incorrectFormulas.size(); i++) {
                    System.out.println("  " + (i + 1) + ". " + incorrectFormulas.get(i));
                }
                
            } else {
                System.out.println("识别失败，错误码: " + result.getCode());
                System.out.println("错误信息: " + result.getMessage());
            }
            
        } catch (Exception e) {
            System.err.println("处理识别结果时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 